package com.example.autopera.读写锁;


import com.amazonaws.services.dynamodbv2.xspec.S;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantReadWriteLock;

class MyCache {

    // 创建map集合
    private volatile Map<String, String> map = new HashMap<>();
    // 创建读写锁
    ReentrantReadWriteLock rwLock = new ReentrantReadWriteLock();


    // 放数据
    public void put(String key, String value) {
        // 添加写锁
        rwLock.writeLock().lock();
        try {
            // 干活
            System.out.println(Thread.currentThread().getName() + "正在进行写操作" + key);

            TimeUnit.MICROSECONDS.sleep(new Random().nextInt(800));

            map.put(key, value);

            System.out.println(Thread.currentThread().getName() + "写操作完成");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 释放写锁
            rwLock.writeLock().unlock();
        }

    }

    // 读数据
    public String get(String key) {
        // 添加读锁
        rwLock.readLock().lock();
        String result = null;
        try {

            // 干活
            System.out.println(Thread.currentThread().getName() + "正在进行读操作" + key);

            TimeUnit.MICROSECONDS.sleep(new Random().nextInt(800));

            result = map.get(key);

            System.out.println(Thread.currentThread().getName() + "读操作完成");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 释放读锁
            rwLock.readLock().unlock();
        }
        return result;
    }


}

public class ReadWriteLockDemo {

    public static void main(String[] args) {
        // 创建读写锁实例
        MyCache cache = new MyCache();

        for (int i = 1; i <= 5; i++) {
            final String num = String.valueOf(i);
            new Thread(() -> {
                cache.put(num, num);
            }, String.valueOf(i)).start();
        }

        for (int i = 1; i <= 5; i++) {
            final String num = String.valueOf(i);
            new Thread(() -> {
                cache.get(num);
            }, String.valueOf(i)).start();
        }

    }

}
